//
//  FirmwareService.m
//  CoolTennisBall
//
//  Created by CA on 16/5/23.
//  Copyright © 2016年 CoolLang. All rights reserved.
//

#import "FirmwareService.h"
#import "CommunicationManager.h"
#import "VersionItem.h"
#import "NSString+Extension.h"
#import "UpdateFirmwaveViewController.h"
#import "NSString+Extension.h"

@interface FirmwareService ()
@property (nonatomic, copy) BeginUpdateFirmwareBlock block;
@property (nonatomic, copy) CheckFirmwareVersionCompletionBlock checkVersionBlock;
@property (nonatomic, assign) FirmwareAlertType type;
@end

@implementation FirmwareService

- (void)performRequestFirmwave:(FirmwareAlertType)alertType beginUpdateFirmwareBlock:(BeginUpdateFirmwareBlock)block checkVersionCompletionBlock:(CheckFirmwareVersionCompletionBlock)checkVersionBlock
{
    self.block = block;
    self.checkVersionBlock = checkVersionBlock;
    self.type = alertType;
    
    if ([[CommunicationManager shareInstance] isDFUMode]) {
        [self performRequestNetworkFirmwareCompareWithLocalVersion:nil];
    } else {
        [[CommunicationManager shareInstance] performOperationType:OperationTypeBatteryRead object:nil completionBlock:^(BOOL batteryReadSuccess, id feedbackData) {
            if (batteryReadSuccess) {
                [BTHandler handleBatteryData:feedbackData withCompletion:^(NSInteger batteryValue) {
                    if (batteryValue > 50) {
                        [[CommunicationManager shareInstance] performOperationType:OperationTypeDeviceVersion object:nil completionBlock:^(BOOL success, id feedbackData) {
                            if (success) {
                                [BTHandler handleDeviceVersionData:feedbackData withCompletion:^(BOOL versionSuccessful, NSString *version) {
                                    if (versionSuccessful) {
                                        [self performRequestNetworkFirmwareCompareWithLocalVersion:version];
                                    }else{
                                        [MBProgressHUD showFailHudInView:MyTabbarView message:NSLocalizedString(@"Fail", nil) afterDelay:1];
                                    }
                                }];
                            }
                        }];
                    } else {
                        if (self.type == FirmwareAlertTypeNormal) {
                            NSLog(@"弹出电量不足提示窗口");
                            
                            FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedStringFromTable(@"reminder", @"Location", nil) message:NSLocalizedString(@"Low battery. Please try again after charging the device", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedStringFromTable(@"OK", @"Location", nil), nil];
                            [alertView customizeAppearance];
                            [alertView show];
                        }
                    }
                }];
            }
        }];
    }
}

- (void)performRequestNetworkFirmwareCompareWithLocalVersion:(NSString *)localVersion
{
    MBProgressHUD *hud = nil;
    if (self.type == FirmwareAlertTypeNormal) {
        hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow.rootViewController.presentedViewController.view animated:YES];
    }
    
    [YFSensorApi getLastDeviceVersionWithOemType:[CommunicationManager shareInstance].lgPeripheral.oemType withComplete:^(BOOL success,YFSensorApi *resultApi, VersionItem *item, NSError *error) {
       
        if (success) {
            if (self.checkVersionBlock) {
                self.checkVersionBlock();
                self.checkVersionBlock = nil;
            }
            DeviceInfo *deviceItem = [User getLastUser].userDevice;
            [[RLMRealm defaultRealm] beginWriteTransaction];
            deviceItem.locationVersion = localVersion;
            deviceItem.serverVersion = item.version;
            [[RLMRealm defaultRealm] commitWriteTransaction];
            
            if (self.type == FirmwareAlertTypeNormal) {
                if (![NSString checkIsLastestVersion:item.version lastestVersion:localVersion]) {
                    
                    FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Reminder", nil) message:[NSString stringWithFormat:NSLocalizedString(@"Make sure device power is greater than 50%% before upgrade,Current firmware is %@,new firmware version %@ is available, upgrade?", nil), [NSString checkIfNullWithString:localVersion], [NSString checkIfNullWithString:item.version]] delegate:nil cancelButtonTitle:NSLocalizedString(@"Skip", nil) otherButtonTitles:NSLocalizedString(@"Upgrade", nil), nil];
                    [alertView customizeAppearance];
                    [alertView show];
                    
                    alertView.onOkAction = ^{
                        
                        [[YFNetworkingService sharedInstance] performDownloadNewVersionWithPath:item.downloadPath downloadCompletionBlock:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
                            if (!error) {
                                [self updateFirmwaveWithFilePath:filePath];
                            } else {
                                [hud showFailHudInView:MyTabbarView message:NSLocalizedString(@"Poor network, Try again later", nil) afterDelay:1];
                            }
                        }];
                    };
                    
                } else if (localVersion != nil) {
                    
                    FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedStringFromTable(@"reminder", @"Location", nil) message:[NSString stringWithFormat:@"%@:%@\n%@",LOCATION(@" firmware versions ") ,localVersion, LOCATION(@"Your firmware is already the latest version")] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedStringFromTable(@"OK", @"Location", nil), nil];
                    [alertView customizeAppearance];
                    [alertView show];
                    
                } else {
                    [[YFNetworkingService sharedInstance] performDownloadNewVersionWithPath:item.downloadPath downloadCompletionBlock:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
                        if (!error) {
                            [self updateFirmwaveWithFilePath:filePath];
                        } else {
                            [hud showFailHudInView:MyTabbarView message:NSLocalizedString(@"Poor network, Try again later", nil) afterDelay:1];
                        }
                    }];
                }
            }else {
                if (![NSString checkIsLastestVersion:item.version lastestVersion:localVersion]) {
                    
                    FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Your device can be upgraded!", nil) message:NSLocalizedString(@"New update available （size 50Kb），download now？", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"Next Time", nil) otherButtonTitles:NSLocalizedString(@"Firmware.OK", nil), nil];
                    [alertView customizeAppearance];
                    [alertView show];
                    
                    alertView.onOkAction = ^{
                        [[YFNetworkingService sharedInstance] performDownloadNewVersionWithPath:item.downloadPath downloadCompletionBlock:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
                            if (!error) {
                                [self updateFirmwaveWithFilePath:filePath];
                            } else {
                                [hud showFailHudInView:MyTabbarView message:NSLocalizedString(@"Poor network, Try again later", nil) afterDelay:1];
                            }
                        }];  
                    };
                }
            }
              [hud hideAnimated:YES];
        }else {
            [hud showFailHudInView:MyTabbarView message:NSLocalizedString(@"Poor network, Try again later", nil) afterDelay:1];
        }
    }];
    
}

- (void)updateFirmwaveWithFilePath:(NSURL *)filePath
{
    UpdateFirmwaveViewController *controller = [[UpdateFirmwaveViewController alloc] initWithNibName:@"UpdateFirmwaveViewController" bundle:nil];
    
    controller.filePathUrl = filePath;
    [controller presentInParentViewController:[UIApplication sharedApplication].keyWindow.rootViewController.presentedViewController];
    
    if (self.block) {
        self.block(YES);
        self.block = nil;
    }
}

#pragma mark - LifeCycle

+ (instancetype)sharedInstance
{
    static id sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    
    dispatch_once(&oncePredicate, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

@end
